package com.fragrance.interceptor;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fragrance.util.Constants;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.plugin.redis.Redis;

/**
 * 是否登录拦截器
 * 
 * @author zhilin
 *
 */
public class LoginInterceptor implements Interceptor {

	private Logger logger = LoggerFactory.getLogger(Interceptor.class);

	public void intercept(Invocation inv) {
		logger.info("========开始登陆拦截========");
		Controller controller = inv.getController();
		HttpServletRequest request = controller.getRequest();
		String requestURL = request.getRequestURI();
		logger.info("requestURL = {}", requestURL);
		if (requestURL.contains("/open/") || requestURL.contains("/addDeviceByExcle")) {
			// 不需要登录
			logger.info("========不需要登录分支========");
			inv.invoke();
		} else {
			// 需要登录
			logger.info("========需要登录分支========");
			String token = request.getParameter("token");
			try {
				if (StringUtils.isEmpty(token)) {
					Map<String, String> result = new HashMap<String, String>();
					logger.info("========没有token参数========");
					result.put("code", Constants.ERROR_CODE);
					result.put("msg", Constants.ERROR_MSG);
					controller.renderJson(result);
					return;
				} else {
					String userInfo = Redis.use("users").get(token);
					if (StringUtils.isBlank(userInfo)) {
						logger.info("========用户没有登录或者token过期========");
						// 用户没有登录
						Map<String, String> result = new HashMap<String, String>();
						result.put("code", Constants.ERROR_CODE_3);
						result.put("msg", Constants.ERROR_MSG_3);
						controller.renderJson(result);
						return;
					} else {
						// 用户已登录
						Redis.use("users").setex(token, 24 * 60 * 60, userInfo);
						inv.invoke();
					}
				}
			} catch (Exception e) {
				logger.error("登录拦截器发生异常", e);
				throw new RuntimeException("登录拦截器发生异常");
			} 
		}
	}

}
